using Microsoft.AspNetCore.Mvc;
using newsApi.Models;
using newsApi.Services;

namespace newsApi.Controllers;
[ApiController]
[Route("api/[controller]")]

public class NewsController:ControllerBase
{
     private readonly NewsService _newsSerVice;

    public NewsController(NewsService newsSerVice) =>
        _newsSerVice = newsSerVice;

    [HttpGet]
    public async Task<List<News>> Get() =>
        await _newsSerVice.GetAsync();

    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<News>> Get(string id )
    {
        var news = await _newsSerVice.GetAsync(id);
        if (news is null)
        {
            return NotFound();
        }
        return news;
    }

    [HttpPost]
    public async Task<IActionResult> Post(News news)
    {
        await _newsSerVice.CreateNews(news);
        return CreatedAtAction(nameof(Get), new { id = news.Id }, news);
    }

    [HttpPut("{id:length(24)}")]
    public async Task<IActionResult> Update(string id, News updatedNews)
    {
        var news = await _newsSerVice.GetAsync(id);
        if (news is null)
        {
            return NotFound();
        }
        updatedNews.Id = news.Id;
        await _newsSerVice.UpdateNews(id,updatedNews);
        return NoContent();
    }

    [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> Delete(string id)
    {
        var news = await _newsSerVice.GetAsync(id);
        if (news is null)
        {
            return  NotFound();
        } 
        await  _newsSerVice.RemoveNews(id);
        return NoContent();   
    }
}